#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

class Solution
{
public:
    static vector<vector<int>> fourSum(vector<int>& nums, const int target)
    {
        sort(nums.begin(), nums.end());
        vector<vector<int>> vv;

        size_t n = nums.size();
        for(int a=0; a<n;)
        {
            for(int b=a+1; b<n;)
            {
                int left = b+1;
                int right = n-1;
                while(left < right)
                {
                    long long sum = nums[left] + nums[right];
                    long long dif = (long long)target-nums[a]-nums[b];
                    if(sum < dif)
                        left++;
                    else if(sum > dif)
                        right--;
                    else
                    {
                        vv.push_back({nums[a], nums[b], nums[left], nums[right]});
                        left++;
                        right--;
                        while(left < right && nums[left]==nums[left-1])
                            left++;
                        while(left < right && nums[right] == nums[right+1])
                            right--;
                    }
                }
                b++;
                while(b<n && nums[b] == nums[b-1])
                    b++;
            }
            a++;
            while(a<n && nums[a] == nums[a-1])
                a++;
        }
        return vv;
    }
};
